import { BusinessItemListInfo } from "../../types/business";
import { clone, findIndex, get, pick, set } from "lodash";
import { RefObject } from "react";
import { Form, FormInstance, Input, Slider } from "antd";
import Dialog from "../Dialog";
import ImageListUpload from "./ImageListUpload";
import request from "../../utils/request";

export const characterDialog = (data?: BusinessItemListInfo) => {
  const isModify = !!data;
  //@ts-ignore
  let newData: BusinessItemListInfo = clone(data);
  const initialData = {
    name: "",
    media_info: [],
    threshold: 0.8,
    score: 1
  };
  if (isModify) {
    initialData.name = data.name;
    // @ts-ignore
    initialData.media_info = get(data, "media_info", []);
    initialData.threshold = get(data, "threshold", 0);
    initialData.score = get(data, "score", 0);
  }
  return new Promise((resolve, reject) => {
    let formRef: RefObject<FormInstance>;

    const onDelete = (item: any) => {
      if (!formRef.current) return;
      const list = formRef.current.getFieldValue("media_info") || [];
      const idx = findIndex(list, { media_url: item?.media_url });
      if (idx !== -1) {
        list.splice(idx, 1);
        formRef.current.setFieldValue("media_info", clone(list));
      }
    };

    const formatUploadInfo = async (url: string) => {
      const info = await request.post("/hyqz/validate/pic", {
        type: 0,
        url,
      });
      return {
        media_url: url,
        ...info,
      };
    };

    Dialog({
      title: isModify ? "人物编辑" : "人物创建",
      width: 600,
      content: (
        <Form initialValues={initialData} getFormRef={(v) => (formRef = v)}>
          <Form.Item label="人物名称" name="name">
            <Input />
          </Form.Item>
          <Form.Item label="上传人脸" name="media_info">
            <ImageListUpload
              addLabel="新增人脸"
              createItem={formatUploadInfo}
              onDelete={onDelete}
            />
          </Form.Item>
          <Form.Item label="阈值" name="threshold">
            <Slider min={0} max={1} step={0.01} />
          </Form.Item>
          <Form.Item label="分数" name="score">
            <Slider min={0} max={10} />
          </Form.Item>
        </Form>
      ),
      onOk: (values, hidden) => {
        if (!isModify) {
          newData = {};
        }
        Object.assign(newData, pick(values, ["name", "score", "threshold"]));
        set(newData, "media_info", clone(values.media_info));

        resolve(newData);
        hidden();
      },
      onCancel: reject,
    });
  });
};
